package br.ufpe.cin.sm.nninn.maps;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import br.ufpe.cin.sm.nninn.util.Utils;

import android.util.Log;

public class Maps {
	
	public static ArrayList<HashMap<String, String>> getLocations(String location) {
		
		String url = "http://maps.google.com/maps/geo?q=" + checkString(location) + "&zoom=6&output=json&sensor=false";

		JSONObject json = Utils.getJSONfromURL(url);
		ArrayList<HashMap<String, String>> locations = new ArrayList<HashMap<String, String>>();
		
		try {
			// Get the element that holds the earthquakes ( JSONArray )

			JSONArray placeMarks = json.getJSONArray("Placemark");
			// JSONObject points = placeMarks.getJSONObject(index)
			// JSONArray placeMarks = json.getJSONArray("Placemark");
			// Loop the Array
			for (int i = 0; i < placeMarks.length(); i++) {

				HashMap<String, String> map = new HashMap<String, String>();

				JSONObject infos = placeMarks.getJSONObject(i);
				JSONObject point = infos.getJSONObject("Point");
				JSONArray coord = point.getJSONArray("coordinates");

				map.put("longitude", coord.getString(0));
				map.put("latitude", coord.getString(1));
				//map.put("magnitude", coord.getString(2));
				locations.add(map);
			}
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}
		
		return locations;
	}
	
	public static String checkString (String url) {
		if (!url.equals("")) {
			url = url.replaceAll(" ", "+");
		}
		return url;
	}
}
